<template>
  <div class="classroom-review">
    <!-- 筛选条件 -->
    <condition-card @reset="reset" @search="initData">
      <el-row>
        <el-col :span="8">
          <el-form-item label="学期">
            <CalendarSelect v-model="query.calendarId" :defaulted="true" @change="changeCalendar"  @load-done="calendarLoadDone" :all="true"></CalendarSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用途">
            <DictSelect :plzSelect="true" v-model="query.borrowingUse" :data="options.useing" :clearable="true" :exclude="usageExclude" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.tower')">
            <DictSelect :plzSelect="true" v-model="query.towerCode" :clearable="true" :data="teachingBuildingArr" :filterable="true" ></DictSelect>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.campus')">
            <DictSelect :plzSelect="true" v-model="query.campus" :data="options.campus" :clearable="true" @change="handelCampusChang" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('classroom.name')">
            <el-input type="text" v-model="query.classroomName" :placeholder="$t('message.plsInput')" :clearable="true" maxlength="15" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借用人">
            <el-input type="text" v-model="query.borPerson" placeholder="请输入" :clearable="true" maxlength="15" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="审核状态">
            <DictSelect :plzSelect="true" v-model="query.applyStatus" :data="options.applyStatus" :exclude="excludeApplyStatus" :clearable="true" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借用说明">
            <el-input type="text" v-model="query.borExplain" placeholder="请输入" :clearable="true" maxlength="15" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="学院" prop="borDepartment">
            <DictSelect :plzSelect="true" placeholder="请选择" v-model="query.borDepartment" :data="options.borDepartment" @change="handelCampusChang" :clearable="true" :disabled="isdisabled" ></DictSelect>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="借用时间">
            <el-date-picker v-model="query.borTimeLong" :editable="editable" :clearable="true" type="date" value-format="timestamp" style="width:100%;" ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </condition-card>

    <!-- 教室借用审核列表 -->
    <el-card shadow="never">
      <!-- <h2>教室借用审核</h2> -->
      <div class="edu-opertion-bar">
        <div class="float-left">
          <el-input v-model="query.conditionValue" :placeholder="'请输入教室名称/教学楼'" suffix-icon="el-icon-search" style="width:240px" 
          maxlength="15" :clearable="true" @change="handSearchChang" />
        </div>
        <div class="float-right">
          <el-button @click="exprotReviewInfo">{{$t("message.export")}}</el-button>
          <el-button type="primary" @click="batchApproved" v-show="!isPropertyStaff">批量通过</el-button>
        </div>
        <div class="clear-both"></div>
      </div>
      <EduTable :order="false" :data="auditList.data" :total="auditList.total" :pageSize="query.pageSize_" :pageNum="query.pageNum_" class="classroomTable"
        @page-change="pageChange" @selection-change="handleSelectionChange" >
        <el-table-column label="借用说明" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.borExplain}}</span>
          </template>
        </el-table-column>
        <el-table-column label="借用用途" min-width="60">
          <template slot-scope="scope">{{scope.row.borrowingUseI18n}}</template>
        </el-table-column>
        <el-table-column label="教室名称" min-width="90" show-overflow-tooltip>
          <template slot-scope="scope">
            <!-- <span :title="scope.row.classroomNameStr.split('|').join('\n')" v-html="scope.row.classroomNameShortStr"></span> -->
            <span>{{scope.row.classroomNameShortStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="教学楼" min-width="70" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :title="scope.row.towerNameStr.split('|').join('\n')" v-html="scope.row.towerNameShortStr"></span>
          </template>
        </el-table-column>
        <el-table-column label="校区" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.campusStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="借用学期" min-width="80" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{scope.row.calendarNameStr}}</span>
          </template>
        </el-table-column>
        <el-table-column label="借用时间" min-width="240" >
          <template slot-scope="scope">
            <span :title="scope.row.mergeBorTimeStr.split('|').join('\n')" v-html="scope.row.mergeBorTimeShortStr"></span>
          </template>
        </el-table-column>
        <el-table-column label="借用人" min-width="80">
          <template slot-scope="scope">
            <el-tooltip placement="top" :content="scope.row.borPerson" effect="light">
              <span>{{scope.row.borPerson}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" min-width="60">
          <template slot-scope="scope">
            <el-tag size="mini" type="info" v-if="scope.row.applyStatus == '1' || scope.row.applyStatus === null">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="danger" v-if="scope.row.applyStatus == '2'">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="success" v-if="scope.row.applyStatus == '3'">{{scope.row.applyStatusI18n}}</el-tag>
            <el-tag size="mini" type="warning" v-if="scope.row.applyStatus == '4'">{{scope.row.applyStatusI18n}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('message.operating')" min-width="60">
          <template slot-scope="scope" >
            <div v-show="!isPropertyStaff">
              <el-button type="text" v-if="scope.row.applyStatus != '1'" size="mini" @click="showRollDetail_1(scope.row)" >查看</el-button>
              <el-button type="text" v-if="scope.row.applyStatus == '3'" size="mini" @click="showRollDetailBack(scope.row)" >撤销</el-button>
              <el-button type="text" v-if="scope.row.applyStatus == '1'" size="mini" @click="showRollDetail_2(scope.row)">审核</el-button>
            </div>
          </template>
        </el-table-column>
      </EduTable>
    </el-card>
  </div>
</template>

<script>
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import * as API from "common/src/api/resource/classroom";
export default {
  name: "classroomReview",
  data() {
    return {
      query: {
        pageNum_: 1,
        pageSize_: 20,
        calendarId: "",
        borrowingUse: "",
        towerCode: "",
        campus: "",
        name: "",
        borPerson: "",
        status: "",
        borExplain: "",
        conditionValue: "",
        borTimeLong:"", projectId:"",
        ids: []

        // departmentCode: ''
      },
      teachingBuildingArr: [],
      defaultQuery: {
        pageNum_: 1,
        pageSize_: 20,
        calendarId: "",
        borrowingUse: "",
        towerCode: "",
        campus: "",
        name: "",
        borPerson: "",
        status: "",
        borExplain: "",
        conditionValue: "",
        borTimeLong:"", projectId:"",
        ids: []
      },
      options: {
        useing: [],
        borDepartment: [],
        campus: [],
        applyStatus: []
      },
      auditList: {
        data: [],
        total: 0
      },
      //当前学期
      currentTermCalendar: "",
      selectData: [],
      //排除教室用途为 排考、排课 借用专用的用途
      usageExclude: ["01", "02"],
      //筛选框去除已撤回状态的选择条件
      excludeApplyStatus: ["4"],
      isPropertyStaff: false
    };
  },
  methods: {
    //物业人员禁止操作按钮
    getIsPropertyStaff(){
      let mockerUser = this.$store.getters.getMockUser();
      let user = mockerUser ? mockerUser:this.$store.getters.getUser();
      let deptCode = user.faculty;
      if (deptCode === '000074' || deptCode === '000054') {
        this.isPropertyStaff = true;
      } else {
        this.isPropertyStaff = false;
      }
    },
    // 获取下拉框数据（数据字典）
    initOptions() {
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_XQ", "X_JSYT", "X_YX", "X_JSSHZT"]
      };
      queryDic(data).then(res => {
        if (res.code == 200) {
          UTILS.fillSelect(
            {
              campus: "X_XQ",
              useing: "X_JSYT",
              borDepartment: "X_YX",
              applyStatus: "X_JSSHZT"
            },
            res.data,
            this.options
          );
        }
      });
    },

    // 查询数据
    initData() {
      this.query.pageNum_ = 1;
      this.query.projectId = this.$store.getters.getProjectId();
      this.getClassroomReviewInfoList();
    },
    async getClassroomReviewInfoList() {
      let res = await API.getClassroomReviewInfoList(this.query);
      if (res && res.code == 200) {
        _.forEach(res.data.list, item => {
          item.classroomNameStr = this.getClassroomNameStrByList(
            item.classroomApplyDetailVoList
          );
          item.classroomNameShortStr = this.convertClassroomNameListStr(item.classroomApplyDetailVoList);
          if(item.mergeBorTimeStr){
            item.mergeBorTimeShortStr = this.convertmergeBorTimeStr(item.mergeBorTimeStr.split('|'));
          }
          item.campusStr = this.getCampusStrByList(
            item.classroomApplyDetailVoList
          );
          item.towerNameStr = this.getTowerNameStrByList(
            item.classroomApplyDetailVoList
          );
          item.towerNameShortStr = this.convertTowerNameListStr(item.classroomApplyDetailVoList);
          item.calendarNameStr = this.getCalendarNameStrByList(
            item.classroomApplyDetailVoList
          );
        });
        this.auditList.data = res.data.list;
        this.auditList.total = res.data.total_;
        this.query.pageSize_ = res.data.pageSize_;
        this.query.pageNum_ = res.data.pageNum_;
      }
    },
    convertClassroomNameListStr(list) {
      if (!list)
        return "";
      if (list.length){
        let tempList = list.map(t => `${t.classroomName}`);
        let uniqueList = [...new Set(tempList)];
        return uniqueList && uniqueList.length ? uniqueList.reduce((a, b) => a +(",") + b) : "";
      }
    },
    convertTowerNameListStr(list) {
      if (!list)
        return "";
      if (list.length){
        let tempList = list.map(t => `${t.towerName}`);
        let uniqueList = [...new Set(tempList)];
        return uniqueList && uniqueList.length ? uniqueList.reduce((a, b) => a +(",") + b) : "";
      }
    },
    convertmergeBorTimeStr(list){
      if (!list)
        return "";
      if (list.length){
      return list && list.length ? list.map(t => `${t}`).reduce((a, b) => a +(",") + b) : "";
      }
    },
    //把教室名称数据转换成需要展示的样子
    getClassroomNameStrByList(list) {
      let str = "";
      let tempList = [];
      if (list != null) {
        list.forEach(index => {
          let classroomName = index.classroomName;
          if (!tempList.includes(classroomName)) {
            str += classroomName + " |";
            tempList.push(classroomName);
          }
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把借用时间转换成需要展示的样子
    getBorTimeStrByList(list) {
      let str = "";
      if (list != null) {
        list.forEach(index => {
          str += index.borTimeStr + " |";
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    //把校区数据转换成需要展示的样子
    getCampusStrByList(list) {
      let str = "";
      if (list != null) {
        str = list[0].campusI18n;
      }
      return str;
    },
    //把学期数据转换成需要展示的样子
    getCalendarNameStrByList(list) {
      let str = "";
      if (list != null) {
        str = list[0].calendarName;
      }
      return str;
    },
    //把校区数据转换成需要展示的样子
    getTowerNameStrByList(list) {
      let str = "";
      let towerNameList = [];
      if (list != null) {
        list.forEach(index => {
          let towerName = index.towerName;
          if (towerName && !towerNameList.includes(towerName)) {
            towerNameList.push(index.towerName);
            str += index.towerName + " |";
          }
        });
        str = str.substr(0, str.length - 1);
      }
      return str;
    },
    // 获取教学楼数据方法 (根据校区获取)
    handelCampusChang(item = null) {
      this.teachingBuildingArr = [];
      this.query.towerCode = "";
      // let params = {
      //   campus: item
      // };
      //条件框教学楼受校区、部门联动 2019-12-04
      let params = {
        campus: this.query.campus,
        departmentCode: this.query.borDepartment
      };
      API.conditionQueryByDict(params).then(res => {
        _.forEach(res.data.list, item => {
          this.teachingBuildingArr.push({
            value: item.code,
            label: item.name
          });
        });
      });
    },
    calendarLoadDone(list) {
      if (list) {
        this.allCalendarList = list;
        for (let index = 0; index < list.length; index++) {
          const element = list[index];
          if (element.currentTermFlag) {
            this.currentTermCalendar = element.id;
            this.totalWeekNumber = element.weekNum;
            break;
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.query.ids = val.map(item => {
        return item.id;
      });
      this.selectData = val;
    },
    // 分页功能
    pageChange(val) {
      this.query.pageNum_ = val.pageNum;
      this.query.pageSize_ = val.pageSize;
      this.getClassroomReviewInfoList();
    },
    //批量通过
    batchApproved() {
      if (this.query.ids.length == 0) {
        this.$message({ type: "warning", message: "请选择需要批量通过的数据！" });
        return;
      }
      let flag = false;
      let tempSelectData = this.selectData;
      tempSelectData.forEach(idndex => {
        if (idndex.applyStatus !== "1") {
          flag = true;
        }
      });
      if (flag) {
        this.$message({ type: "warning", message: "需要批量通过的数据状态应都为待审核！" });
        return;
      }
      API.batchApproved(this.query.ids).then(res => {
        if (res && res.code === 200) {
          this.$message({ type: "success", message: res.msg });
          this.getClassroomReviewInfoList();
        } else {
          this.$message({ type: "info", message: "批量通过失败，当前操作人不是审核人!" });
        }
      });
    },
    //导出
    exprotReviewInfo() {
      let res = API.exprotReviewInfo(this.query);
    },
    reset() {
      this.query = JSON.parse(JSON.stringify(this.defaultQuery));
      //学期为当前学期
      this.query.calendarId = this.currentTermCalendar;
      this.getClassroomReviewInfoList();
      this.handelCampusChang(null);
    },
    // 查看
    showRollDetail_1(row) {
      let workflowNo = row.workflowNo;
      this.$router.push({
        path: "/TeacherRollDetail",
        query: {
          //2为更新教室借用申请单
          id: workflowNo,
          commentFlag: true
        }
      });
    },
    // 审核
    showRollDetail_2(row) {
      let workflowNo = row.workflowNo;
      this.$router.push({
        path: "/TeacherRollDetail",
        query: {
          //2为更新教室借用申请单
          id: workflowNo,
          commentFlag: false
        }
      });
    },
    // 撤销
    showRollDetailBack(row) {
      let workflowNo = row.workflowNo;
      let borExplain = row.borExplain;
      let id = row.id;
      this.$delConfirm("确定要撤销 [ "+borExplain+" ] 吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        API.updateClassroomApplyStatusBack(id).then(res =>{
          if (res.code == 200) {
              this.$message({ type: "success", message: "'" + borExplain + "'" + " 撤销成功!" });
              this.initData();
            } else {
              this.$message({ type: "info", message: res.msg });
            }
        });
      }).catch(e => {});
    },

    handSearchChang(string) {
        this.initData();
    },
  },
  watch: {
    $route() {
      //1 表示此页面为新增页面
      this.getClassroomReviewInfoList();
      this.handelCampusChang(null);
    }
  },
  created() {
    this.initOptions();
    this.getIsPropertyStaff();
    this.getClassroomReviewInfoList();
    this.handelCampusChang(null);
  }
};
</script>

<style lang="scss">
  .classroomTable{
    .cell{
      white-space: pre-line;
	  padding: 0 2px;
	  text-align: center;
    }
  }
</style>

